package com.hazardousholdings.unkj.validation;

/**
 * IntegerValidator validates that input is an integer.
 * If input is null or empty, IntegerValidator will return true with the default value.
 */
public class IntegerValidator implements ParsingValidator<Integer> {

	private Integer defaultValue;
	private String failureMessage = null;
	
	public IntegerValidator() {
		this(0);
	}
	
	public IntegerValidator(Integer defaultValue) {
		this.defaultValue = defaultValue;
	}

	@Override
	public String getInvalidMessage() {
		if(failureMessage == null) {
			return "Input must be an integer";
		} else {
			return this.failureMessage;
		}
	}
	
	@Override
	public void setInvalidMessage(String message) {
		this.failureMessage = message;
	}
	
	@Override
	public ValidationResults<Integer> validate(String input) {
		Integer result = this.defaultValue;
		
		if(input == null || input.isEmpty()) {
			return new ValidationResults<Integer>(result, true);
		} else {
			try {
				result = new Integer(input);
				return new ValidationResults<Integer>(result, true);
			} catch(NumberFormatException ex) {
				return new ValidationResults<Integer>(result, false, this.getInvalidMessage());
			}
		}
	}

	@Override
	public ValidationResults<Integer> validate(Integer input) {
		return new ValidationResults<Integer>(input, true);
	}

	
	
}
